package com.example.musicdemo1.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.musicdemo1.R
import com.example.musicdemo1.model.PlaylistItem
import com.example.musicdemo1.service.MusicPlayer

class PlaylistAdapter(private val playlist: List<PlaylistItem>) : 
    RecyclerView.Adapter<PlaylistAdapter.ViewHolder>() {

    init {
        MusicPlayer.setPlaylist(playlist)
    }

    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val coverImage: ImageView = view.findViewById(R.id.coverImage)
        val titleText: TextView = view.findViewById(R.id.titleText)
        val singerText: TextView = view.findViewById(R.id.singerText)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_playlist, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = playlist[position]
        holder.titleText.text = item.title
        holder.singerText.text = item.singer
        
        Glide.with(holder.coverImage)
            .load(item.coverImgUrl)
            .placeholder(R.drawable.ic_music_note)
            .error(R.drawable.ic_music_note)
            .into(holder.coverImage)

        holder.itemView.setBackgroundResource(
            if (MusicPlayer.currentMusic.value?.id == item.id) 
                android.R.color.darker_gray 
            else 
                android.R.color.transparent
        )

        holder.itemView.setOnClickListener {
            MusicPlayer.play(item)
        }
    }

    override fun getItemCount() = playlist.size
} 